import logging
import os
import time

# 自定义过滤器
class infoFilter(logging.Filter):
    def filter(self, record):
        return record.levelno == logging.INFO

class errFilter(logging.Filter):
    def filter(self, record):
        return record.levelno == logging.ERROR


class Logger:
    """
    日志类
    """

    @classmethod
    def getlog(cls):
        # 创建日志对象
        cls.logger = logging.getLogger(__name__)
        cls.logger.setLevel(logging.DEBUG)

        # 保证logs文件夹存在
        log_path = "./logs/"
        if not os.path.exists(log_path):
            os.mkdir(log_path)

        '''
        将日志输出到对应的日志文件中
        '''
        # 获取当前时间
        now = time.strftime("%Y-%m-%d")
        # 拼接日志文件名
        log_name = log_path + now + '.log'
        info_log_name = log_path + now + '-info.log'
        err_log_name = log_path + now + '-err.log'

        # 创建文件处理器
        all_handler = logging.FileHandler(log_name, encoding="utf-8")
        info_handler = logging.FileHandler(info_log_name, encoding="utf-8")
        err_handler = logging.FileHandler(err_log_name, encoding="utf-8")

        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        # 设置日志格式
        formatter = logging.Formatter(
            "%(asctime)s %(levelname)s [%(name)s] [%(filename)s (%(funcName)s:%(lineno)d)] - %(message)s"
        )
        all_handler.setFormatter(formatter)
        info_handler.setFormatter(formatter)
        err_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        #添加过滤器
        info_handler.addFilter(infoFilter())
        err_handler.addFilter(errFilter())


        # 添加处理器
        cls.logger.addHandler(all_handler)
        cls.logger.addHandler(info_handler)
        cls.logger.addHandler(err_handler)
        cls.logger.addHandler(console_handler)
        return cls.logger


